<template>
  <MdEditor
    v-model="editContent"
    :theme="theme"
    @onUploadImg="onUploadImg"
    @onChange="editorChange" />
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { MdEditor } from 'md-editor-v3';
  import 'md-editor-v3/lib/style.css';
  import { upLoadImg } from '@/apis/article';
  import { storeToRefs } from 'pinia';
  //   主题
  import { useThemeStore } from '@/stores/themeStore';
  let { theme } = storeToRefs(useThemeStore());
  // 内容 HTML
  const editContent = ref('');
  const props = defineProps({
    modelValue: {
      type: String,
      default: ''
    }
  });
  watch(
    () => props.modelValue,
    val => {
      editContent.value = val;
    }
  );

  const $emit = defineEmits(['update:modelValue']);

  const onUploadImg = async (files: any, callback: any) => {
    const API_URL = import.meta.env.VITE_VUE_UPLOAD_URL;
    Promise.all(
      files.map((file: any) => {
        const form = new FormData();
        form.append('file', file);
        return upLoadImg(form);
      })
    ).then(res => {
      callback(res.map(item => API_URL + item.data.url));
    });
  };
  const editorChange = (v: any) => {
    $emit('update:modelValue', v);
  };
</script>
